var express = require('express');
var router = express.Router();
var pool = require('../db')

console.log(pool);

/* GET users listing. */
router.get('/', function(req, res, next) {
  // nodemon实时更新
  res.send('123456');
});
// 登录接口
router.post('/login',function(req,res,next){
  // post传参 req.body
  // get传参  req.query
  console.log(req.body);
  const { userName,passWord } = req.body

  //查询数据 pool.query
  //带条件进行查询
  pool.query(`select * from user where name='${userName}' and password='${passWord}'`, (err, data) => {
    if (err) {
      res.send({
        code: 0,
        message: "sql语句错误"
      })
    } else {
      // 如果登录成功 返回token  FJLSAKLDNASDOSADI
      // 1. 生成token  (jsonwebtoken)
      if (data.length > 0) {
        const { userId } = data[0]
        // jwt.sign(要生成token的属性, 生成token的规则, token的配置)
        let token = jwt.sign({ userName, userId }, key, {
          expiresIn: "1h"
        })

        // verify 解析token

        console.log(jwt.verify(token, key))

        res.send({
          code: 1,
          message: "登录成功",
          token
        })
      } else {
        res.send({
          code: 0,
          message: "请去注册"
        })
      }
    }
  })
  res.send('我是登录接口')
})
module.exports = router;
